<?php
/**
 * Created by PhpStorm.
 * User: yys
 * Date: 2016/12/5
 * Time: 18:11
 */

namespace App\Http\Controllers\Backstage;
use App\Http\Controllers\Controller;
use App\Services\TagService\TagService;
use App\Services\TagService\TagTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TagBackController extends Controller
{
    protected $tagSer;
    /**
     * TagBackController constructor.
     */
    public function __construct(TagService $tagService)
    {
        $this->tagSer=$tagService;
    }
    /**
     * 标签搜索
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function tagSearch(Request $request){
        $rule=array(
            'search'=>'required|string|',
            'app_id'=>'required|integer|min:1',
            'type'=>'required|integer|min:1',
        );
        $search=$request->input('search','');
        $app_id=intval($request->input('app_id'));
        $type=intval($request->input('type'));
        $validator=TagTool::store($request,$rule);
        if ($validator->fails())
        {
            if($validator->errors()->first('search')){
                $search='';
            }
            if($validator->errors()->first('app_id')){
                $result['state']=-2;
                $result['message']='系统繁忙，请稍后再试';
            }
            if($validator->errors()->first('type')){
                $result['state']=-2;
                $result['message']='系统繁忙，请稍后再试';
            }
            if(!empty($result)){
                return response()->json($result);
            }
        }

        $tags =  $this->tagSer->searchResourceTagList($search,$app_id,$type,array());
        $result=array('data'=>$tags,'state'=>1,'message'=>'获取成功');
        return response()->json($result);
    }

    /**
     * 添加标签
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function addTag(Request $request){
        $rules=array(
            'tag_name' => 'required|string|max:20',
            'description' => 'string|max:180',
            'app_id'=>'required|integer|min:1',
            'tag_type'=>'|integer|min:1',
            'original_image'=>'required|image'
        );
        $description=$request->input('description','');
        $name=trim($request->input('tag_name',''));
        $tag_type=intval($request->input('tag_type'));
        $sort_type=intval($request->input('sort_type'));
        $app_id=intval($request->input('app_id'));
        $p_tag_ids=$request->input('p_tag_ids');
        $original_image=$request->file('original_image');
        $validator=TagTool::store($request,$rules);
        $val_data['name']=$name;
        $val_data['app_id']=$app_id;
        $val_data['tag_type']=empty($tag_type)?2:$tag_type;
        $val_data['sort_type']=empty($sort_type)?2:$sort_type;
        $val_data['p_tag_ids']=$p_tag_ids;
        $val_data['original_image']=$original_image;
        $val_data['description']=$description;
        $validator->after(function($validator) use ($val_data)
        {
            $tag_name_exist=TagTool::tagNameExistByTagNameAndAppId($val_data['name'],$val_data['app_id'],1);
            if($tag_name_exist){
                $validator->errors()->add('tag_name', '已存在');
            }
            $p_tag_ids=$val_data['p_tag_ids'];
            if(!empty($p_tag_ids)){
                foreach ($p_tag_ids as $tag_id){
                    $tag_id=(int)$tag_id;
                    $tag_exist=TagTool::tagExistByTagIdAndAppId($tag_id,$val_data['app_id'],1);
                    if(!$tag_exist){
                        $validator->errors()->add('p_tag_ids', '绑定标签中有不存在的');
                        continue;
                    }
                }
            }
        });
        if ($validator->fails())
        {
            $request->flash();
            return redirect()->back()->withErrors($validator->errors())->withInput();
        }
        $res =  $this->tagSer->addTag($val_data);
        if($res){
            return redirect()->back()->with('success_message', '保存成功');
        }
        return redirect()->back()->with('error_message', '保存失败');
    }

    /**
     * 更新标签
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function updateTag(Request $request){
        $rules=array(
            'tag_name' => 'required|string|max:20',
            'description' => 'string|max:180',
            'app_id'=>'required|integer|min:1',
            'tag_id'=>'required|integer|min:1',
            'tag_type'=>'|integer|min:1',
        );
        $description=$request->input('description','');
        $name=trim($request->input('tag_name',''));
        $app_id=intval($request->input('app_id'));
        $tag_id=intval($request->input('tag_id'));
        $p_tag_ids=$request->input('p_tag_ids');
        $tag_type=intval($request->input('tag_type'));
        $sort_type=intval($request->input('sort_type'));
        $original_image=$request->file('original_image');
        $validator=TagTool::store($request,$rules);
        $val_data['name']=$name;
        $val_data['app_id']=$app_id;
        $val_data['id']=$tag_id;
        $val_data['p_tag_ids']=$p_tag_ids;
        $val_data['original_image']=$original_image;
        $val_data['description']=$description;
        $val_data['tag_type']=empty($tag_type)?2:$tag_type;
        $val_data['sort_type']=empty($sort_type)?2:$sort_type;
        $validator->after(function($validator) use ($val_data)
        {
            $tag_name_exist=TagTool::tagNameExistByTagNameAndAppIdNotCurrentId($val_data['name'],$val_data['app_id'],$val_data['id'],1);
            if($tag_name_exist){
                $validator->errors()->add('tag_name', '已存在');
            }
            $p_tag_ids=$val_data['p_tag_ids'];
            if(!empty($p_tag_ids)){
                foreach ($p_tag_ids as $tag_id){
                    $tag_id=(int)$tag_id;
                    $tag_exist=TagTool::tagExistByTagIdAndAppId($tag_id,$val_data['app_id'],1);
                    if(!$tag_exist){
                        $validator->errors()->add('p_tag_ids', '绑定标签中有不存在的');
                        continue;
                    }
                }
            }
        });
        if ($validator->fails())
        {
            $request->flash();
            return redirect()->back()->withErrors($validator->errors())->withInput();
        }

        $res =  $this->tagSer->updateTag($val_data);
        if($res){
            return redirect()->back()->with('success_message', '保存成功');
        }
        return redirect()->back()->with('error_message', '保存失败');
    }

    /**
     * 标签删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delTag(Request $request){
        $id=intval($request->input('id'));
        $tag_exist=TagTool::tagExistByTagId($id);
        if(!$tag_exist){
            $result['state']=-3;
            $result['message']='数据不存在';
            return response()->json($result);
        }
        $update_result=$this->tagSer->delTagById($id);
        if($update_result){
            $result['state']=1;
            $result['message']='更新成功';
        }else{
            $result['state']=-1;
            $result['message']='更新失败';
        }
        return response()->json($result);
    }

    /***
     * 更新标签排序
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postUpdateSort(Request $request)
    {
        $v=array(
            'id'=>'required|integer|min:1',
            'sort'=>'required|integer|max:9999'
        );
        $validator=$this->tagSer->store($request,$v);
        $id = intval(trim($request->input("id")));
        $sort= intval(trim($request->input("sort")));
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -2;
                $result["message"] = "编号不正确";
                return response()->json($result);
            }
            if($validator->errors()->first('sort')){
                $result["state"] = -3;
                $result["message"] = "排序数字格式不正确";
                return response()->json($result);
            }
        }
        $tag_exist=  TagTool::tagExistByTagId($id,1);
        if(!$tag_exist){
            $result["state"] = -3;
            $result["message"] = "找不到数据";
            return response()->json($result);
        }
        $res =  $this->tagSer->updateTagSort($id,$sort);
        if($res){
            $result["state"] = 1;
            $result["message"] = "更新成功";
            return response()->json($result);
        }else{
            $result["state"] = -1;
            $result["message"] = "更新失败";
            return response()->json($result);
        }
    }
}